<template>
	<a-modal
		v-model:open="visible"
		title="报名选手列表"
		:width="1000"
		:footer="null"
		:maskClosable="false"
		@cancel="onClose"
	>
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:scroll="{ x: 'max-content' }"
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'positions'">
					<a-space wrap>
						<a-tag v-for="pos in parsePositions(record.positions || record.position || record.goodPositions)" :key="pos">
							{{ $TOOL.dictTypeData('player_position', pos) || pos }}
						</a-tag>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-modal>
</template>

<script setup name="playerListModal">
	import matchPlayerApi from '@/api/dota/matchPlayerApi'

	const visible = ref(false)
	const tableRef = ref()
	const matchId = ref(null)

	const toolConfig = { refresh: true, height: false, columnSetting: false, striped: false }

	const parsePositions = (value) => {
		if (!value) {
			return []
		}
		if (Array.isArray(value)) {
			return value
		}
		return String(value)
			.split(',')
			.map((item) => item.trim())
			.filter((item) => item)
	}

	const columns = [
		{
			title: '选手名称',
			dataIndex: 'playName',
			width: 150
		},
		{
			title: '擅长位置',
			dataIndex: 'positions',
			width: 200
		},
		{
			title: '能力值',
			dataIndex: 'ability',
			width: 100
		},
		{
			title: '天梯分',
			dataIndex: 'mmr',
			width: 120
		},
		{
			title: '报名时间',
			dataIndex: 'createTime',
			width: 180
		}
	]

	const loadData = (parameter) => {
		if (!matchId.value) {
			return Promise.resolve({
				data: [],
				total: 0
			})
		}
		
		const params = {
			...parameter,
			matchId: matchId.value
		}
		
		return matchPlayerApi.matchPlayerPage(params).then((data) => {
			return data
		})
	}

	// 打开弹窗
	const onOpen = (record) => {
		visible.value = true
		matchId.value = record.id
		// 延迟加载数据，确保表格已渲染
		nextTick(() => {
			if (tableRef.value) {
				tableRef.value.refresh(true)
			}
		})
	}

	// 关闭弹窗
	const onClose = () => {
		visible.value = false
		matchId.value = null
	}

	// 暴露方法给父组件
	defineExpose({
		onOpen
	})
</script>

<style scoped>
:deep(.ant-modal-body) {
	padding: 20px;
}
</style>

